package com.hua.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hua.entities.*;
import com.hua.service.serviceImpl.CategoryServiceImpl;
import com.hua.service.serviceImpl.DishFlavorServiceImpl;
import com.hua.service.serviceImpl.DishServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishServiceImpl dishService;
    @Autowired
    private CategoryServiceImpl categoryService;
    @Autowired
    private DishFlavorServiceImpl dishFlavorService;


    @PostMapping()
    @Transactional
    public R<String> saveDishAndFlavors(@RequestBody DishDto dishDto) {

        boolean b = dishService.saveAndFlavors(dishDto);
        if (!b) {
            return R.error("新增失败，未知错误");
        }

        return R.success("新增成功");
    }

    @GetMapping("/page")
    public R<Page> getInfo(int page, int pageSize, String name) {
        /*
         * 为什么要copy的时候武略records 因为record对应的就是我们页面中的一条一条的数据，即是Dish
         *  但我们要的是DishDto不符合类型，所以忽略
         *
         * */
        Page<Dish> getPage = new Page<>(page, pageSize);

        LambdaQueryWrapper<Dish> lambdaQueryWrapper
                = new LambdaQueryWrapper<>();

        lambdaQueryWrapper.eq(name != null, Dish::getName, name);

        Page<Dish> page1 = dishService.page(getPage, lambdaQueryWrapper);

        List<Dish> records = page1.getRecords();

        List<DishDto> records1 = null;

        Page<DishDto> getPageInfo = new Page<>();

        //拷贝并忽略records记录
        BeanUtils.copyProperties(getPage, getPageInfo, "records");

        records1 = records.stream().map(item -> {
            DishDto dishDto = new DishDto();
            //拷贝对象
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String getName = category.getName();
            if (getName != null) {
                dishDto.setCategoryName(getName);
            }
            return dishDto;
        }).collect(Collectors.toList());

        getPageInfo.setRecords(records1);

        return R.success(getPageInfo);
    }

    @GetMapping("/{id}")
    @Transactional
    public R<DishDto> getDishInfo(@PathVariable Long id) {
        Dish info = dishService.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(info, dishDto);
        LambdaQueryWrapper<DishFlavor> dishFlavor
                = new LambdaQueryWrapper<>();
        dishFlavor.eq(DishFlavor::getDishId, info.getId());
        List<DishFlavor> list = dishFlavorService.list(dishFlavor);
        dishDto.setFlavors(list);
        return R.success(dishDto);
    }

    @PutMapping()
    @Transactional
    public R<String> updateDishInfo(@RequestBody DishDto dishDto) {
        //改菜品库
        dishService.updateById(dishDto);
        //改类型库
        //改前先删
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper =
                new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(lambdaQueryWrapper);

        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map(item -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);

        return R.success("修改成功");
    }

    @PostMapping("/status/{id}")
    public R<String> updateStatus(@PathVariable Long id, @RequestParam("ids") List<Long> ids) {
        LambdaUpdateWrapper<Dish> lambdaUpdateWrapper
                = new LambdaUpdateWrapper<>();
        if (id == 0L) {
            lambdaUpdateWrapper.set(Dish::getStatus, 0);
        } else {
            lambdaUpdateWrapper.set(Dish::getStatus, 1);
        }
        for (int i = 0; i < ids.size(); i++) {
            /*
            这里不能用eq 因为我们不能清除上一次存进去的id，
            如果用了 查询语句就会变成
            第一次
            set xxx where id = ?
            第二次
            set xxx where id = ? and id= ? ;这肯定不成立- -
            * */
            lambdaUpdateWrapper.in(Dish::getId, ids);
            dishService.update(lambdaUpdateWrapper);
        }

        return R.success("修改成功");

    }

    @DeleteMapping
    @Transactional
    public R<String> deleteById(@RequestParam("ids") List<Long> ids) {

        Dish dish = new Dish();
        for (int i = 0; i < ids.size(); i++) {
            dish = dishService.getById(ids.get(i));
            dishService.removeById(ids.get(i));
            dishFlavorService.removeById(dish.getId());
        }
        return R.success("删除成功");
    }

    //    @GetMapping("/list")
//    public R<List<Dish>> getDishInfoForTaoCan(@RequestParam("categoryId") Long categoryId){
//
//
//        LambdaQueryWrapper<Dish>
//                lambdaQueryWrapper = new LambdaQueryWrapper();
//       lambdaQueryWrapper.eq(categoryId!=null,Dish::getCategoryId,categoryId).orderByAsc(Dish::getStatus).orderByAsc(Dish::getUpdateTime);
//       lambdaQueryWrapper.eq(Dish::getStatus,1);
//       List<Dish> list = dishService.list(lambdaQueryWrapper);
//        if(list.size()==0){
//            return R.error("暂无菜品~~~");
//        }
//        return R.success(list);
//    }
    @GetMapping("/list")
    public R<List<DishDto>> getDishInfoForTaoCan(@RequestParam("categoryId") Long categoryId) {


        LambdaQueryWrapper<Dish>
                lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(categoryId != null, Dish::getCategoryId, categoryId).orderByAsc(Dish::getStatus).orderByAsc(Dish::getUpdateTime);
        lambdaQueryWrapper.eq(Dish::getStatus, 1);
        List<Dish> list = dishService.list(lambdaQueryWrapper);

        List<DishDto> list1 = null;

        list1 = list.stream().map(item -> {
           DishDto dishDto = new DishDto();
           BeanUtils.copyProperties(item,dishDto);
           LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
            Long dishId = item.getId();
            wrapper.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> flavors = dishFlavorService.list(wrapper);
            dishDto.setFlavors(flavors);
            return dishDto;
        }).collect(Collectors.toList());

        if (list.size() == 0) {
            return R.error("暂无菜品~~~");
        }
        return R.success(list1);
    }
}
